//
//  VideoPlayer.m
//  LvXi_newVersion
//
//  Created by 王敏 on 16/11/4.
//  Copyright © 2016年 SJT. All rights reserved.
//

#import "VideoPlayer.h"


typedef NS_ENUM(NSUInteger, SliderState) {
    SliderStateBeginScroll = 0,
    SliderStateEndScroll,
    SliderStateNone,
};

@interface VideoPlayer(){
    MBProgressHUD * _hud;
    AVPlayerItem * _playerItem;
    BOOL _hiddenNaviBar;
}



@property (nonatomic,strong)AVPlayer *player;

@property(nonatomic,strong)AVPlayerLayer * playerLayer;

@property(nonatomic,assign)CGFloat totlaTime;

@property(nonatomic,assign)CGFloat currentTime;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;

@property(nonatomic,weak)IBOutlet UIView * toolContentView;

@property (weak, nonatomic) IBOutlet UILabel *timeInfoLabel;

@property(nonatomic,assign)SliderState slideState;

@end

@implementation VideoPlayer

-(void)awakeFromNib{
    [super awakeFromNib];
    self.backgroundColor =[UIColor redColor];
    self.width = ScreenWidth;
    self.height = ScreenHeight;
    NSLog(@"%s",__func__);
    [self addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHnadle:)]];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHnadle:)]];
    self.player = [AVPlayer playerWithURL:[NSURL URLWithString:self.videoUrl]];
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.videoGravity =  AVLayerVideoGravityResizeAspectFill;
    
    [self.layer addSublayer:self.playerLayer];

    
    [self.progressSlider addTarget:self action:@selector(sliderBeginScroll:) forControlEvents:UIControlEventTouchDown];
    [self.progressSlider addTarget:self action:@selector(sliderEndScroll:) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchCancel];
    
    self.slideState = SliderStateEndScroll;
}

-(void)sliderBeginScroll:(UISlider*)slider{
    self.slideState = SliderStateBeginScroll;
}

-(void)sliderEndScroll:(UISlider*)slider{
    
    [self.player seekToTime:CMTimeMake(slider.value, 1) completionHandler:^(BOOL finished) {
        [self.player play];
        self.slideState = SliderStateEndScroll;
    }];
}

-(void)panGestureHnadle:(UIPanGestureRecognizer*)sender{
    
    CGPoint  point =  [sender translationInView:self];
//    if(point.y>0){
//        [MPMusicPlayerController applicationMusicPlayer].volume += 0.02;
//       
//
//    }else{
//        [MPMusicPlayerController applicationMusicPlayer].volume -= 0.02;
//
//    }
    NSLog(@"%@",NSStringFromCGPoint(point));
}
-(void)tapGestureHnadle:(UIPanGestureRecognizer*)sender{
    
    _hiddenNaviBar = !_hiddenNaviBar;
    self.toolContentView.hidden = _hiddenNaviBar;
    self.timeInfoLabel.y = _hiddenNaviBar?15:49;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenNvigationBar" object:@(_hiddenNaviBar)];


}

-(void)layoutSubviews{
    [super layoutSubviews];
    self.playerLayer.frame = (CGRect){0,0,self.width,self.height};
    self.toolContentView.hidden = _hiddenNaviBar;
    self.timeInfoLabel.y = _hiddenNaviBar?15:49;

}

-(void)setVideoUrl:(NSString *)videoUrl{
    _videoUrl = videoUrl;
    _playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.videoUrl]];
    [self.player replaceCurrentItemWithPlayerItem:_playerItem];
    [self addObserver];
    
    [self bringSubviewToFront:self.toolContentView];
    [self bringSubviewToFront:self.timeInfoLabel];
    
    _hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
}

-(void)play{
    [self.player play];
}

-(void)pause{
    [self.player pause];
}

-(void)dealloc{
    NSLog(@"%s",__func__);
    [self.player removeObserver:self forKeyPath:@"status"];
    [self.player removeObserver:self forKeyPath:@"loadedTimeRanges"];
}


-(void)addObserver{
    WeakSelf(ws);
    [self.player addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.player addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        
        ws.currentTime = time.value*1.0/time.timescale;
        
        ws.timeInfoLabel.text = [NSString stringWithFormat:@"%@  / %@",[NSString formatTime:ws.currentTime],[NSString formatTime:ws.totlaTime]];
        if(ws.slideState == SliderStateEndScroll)
        ws.progressSlider.value=ws.currentTime;
    }];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if([keyPath isEqualToString:@"status"]){
        AVPlayerItem * playerItem = (AVPlayerItem*)object;
        if(playerItem.status == AVPlayerStatusReadyToPlay){
            [_hud hide:YES];
            
            [self.player play];
            [_hud hide:YES];
            self.totlaTime = floor(_playerItem.asset.duration.value*1.0/_playerItem.asset.duration.timescale);
            self.progressSlider.maximumValue = self.totlaTime;
            self.progressSlider.minimumValue = 0;
        }
    }

}


- (NSString *)getStringFromCMTime:(CMTime)time
{
    float currentTimeValue = (CGFloat)time.value/time.timescale;//得到当前的播放时
    
    NSDate * currentDate = [NSDate dateWithTimeIntervalSince1970:currentTimeValue];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSInteger unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond ;
    NSDateComponents *components = [calendar components:unitFlags fromDate:currentDate];
    
    if (currentTimeValue >= 3600 )
    {
        return [NSString stringWithFormat:@"%ld:%ld:%ld",components.hour,components.minute,components.second];
    }
    else
    {
        return [NSString stringWithFormat:@"%ld:%ld",components.minute,components.second];
    }
}



@end


